#include "SDLInput.h"

SDLInput* SDLInput::instance = nullptr;

SDLInput::SDLInput()
{
	SDL_memset(keys, false, sizeof(bool)*KEY_COUNT);
	SDL_memcpy(lastKeys, keys, sizeof(bool)*KEY_COUNT);

	SDL_memset(mouseButtons, false, sizeof(bool)*MOUSE_BUTTON_COUNT);
	SDL_memcpy(lastMouseButtons, mouseButtons, sizeof(bool)*MOUSE_BUTTON_COUNT);
}
void SDLInput::Poll(SDL_Event e)
{
	switch (e.type)
	{
	case SDL_KEYDOWN:
		if(!e.key.repeat)
		{
            lastKeys[e.key.keysym.scancode] = false;
			keys[e.key.keysym.scancode] = true;
		}
		break;
	case SDL_KEYUP:
		lastKeys[e.key.keysym.scancode] = true;
		keys[e.key.keysym.scancode] = false;
		break;
	case SDL_MOUSEMOTION:
		mouseX = e.motion.x;
		mouseY = e.motion.y;
		break;
	case SDL_MOUSEBUTTONDOWN:
		lastMouseButtons[e.button.button] = false;
		mouseButtons[e.button.button] = true;
		break;
	case SDL_MOUSEBUTTONUP:
		lastMouseButtons[e.button.button] = true;
		mouseButtons[e.button.button] = false;
		break;
	default:
		break;
	}
}
bool SDLInput::IsKeyHeld(SDL_Scancode key)
{
	return keys[key];
}
bool SDLInput::IsKeyPressed(SDL_Scancode key)
{
	bool isPressed = !lastKeys[key] && keys[key];
	if(isPressed)
	{
		lastKeys[key] = keys[key];
	}
	return isPressed;
}
bool SDLInput::IsKeyReleased(SDL_Scancode key)
{
	bool isReleased = lastKeys[key] && !keys[key];
	if(isReleased)
	{
		lastKeys[key] = keys[key];
	}
	return isReleased;
}
bool SDLInput::IsMouseButtonHeld(int button)
{
	return mouseButtons[button];
}
bool SDLInput::IsMouseButtonPressed(int button)
{
	bool isPressed = !lastMouseButtons[button] && mouseButtons[button];
	if(isPressed)
	{
		lastMouseButtons[button] = mouseButtons[button];
	}
	return isPressed;
}
bool SDLInput::IsMouseButtonReleased(int button)
{
	bool isReleased = lastMouseButtons[button] && !mouseButtons[button];
	if(isReleased)
	{
		lastMouseButtons[button] = mouseButtons[button];
	}
	return isReleased;
}
void SDLInput::GetMousePosition(int& x, int& y)
{
	x = mouseX;
	y = mouseY;
	return;
}